package cn.tedu.coolsharkmall.service.Impl;

import cn.tedu.coolsharkmall.ex.ServiceException;
import cn.tedu.coolsharkmall.mapper.CategoryMapper;
import cn.tedu.coolsharkmall.pojo.dto.CategoryAddNewDTO;
import cn.tedu.coolsharkmall.pojo.entity.Category;
import cn.tedu.coolsharkmall.pojo.vo.CategoryStandardVo;
import cn.tedu.coolsharkmall.service.ICategoryService;
import cn.tedu.coolsharkmall.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    CategoryMapper mapper;

    @Override
    public void addNew(CategoryAddNewDTO categoryAddNewDTO) {
        //通过参数对象获取parentId
        String name = categoryAddNewDTO.getName();
        int count = mapper.countByName(name);
        log.debug("根据名称【{}】统计数量，结果:{}", name, count);
        if(count > 0){
            String message = "添加类别失败,类别名称已经被占用!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }
        Long parentId = categoryAddNewDTO.getParentId();
        Integer depth;
        CategoryStandardVo parentCategory = null;
        //判断parentId是否为0
        if(parentId == 0){
            //是: depth为固定1
            depth = 1;
        }else{
            //否调用Mapper对象getStandardById()查询parentId
             parentCategory = mapper.getStandardById(parentId);
             log.debug("parentCategory :{}", parentCategory);
            //  判断查询结果(父级类别)是否为null
            if(parentCategory == null){
                //  是，抛出异常
                String message = "添加类别失败,父级类别不存在!";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
            }else{
                //  否:depth(深度值为):父级类别为的depth + 1
                depth = parentCategory.getDepth() + 1;
            }
        }
        log.debug("{}", parentCategory);

        //创建Category对象
        Category category = new Category();
        //复制属性
        BeanUtils.copyProperties(categoryAddNewDTO, category);
        //补全category对象的属性值 depth
        category.setDepth(depth);
        //补全category对象的属性值 isParent >>>0
        category.setIsParent(0);
        //调用mapper对象的insert()方法执行插入
        mapper.insert(category);

        log.debug("{}:{}", parentId, parentCategory.getIsParent());


        //判断parentId是否不为0并判断父级类别的isParent是否为0
        if(parentId != 0 && parentCategory.getIsParent() == 0){
            //  是:考虑是否将父级类别的isParent更新为1
            Category updateParentCategory = new Category();
            updateParentCategory.setId(parentId);
            updateParentCategory.setIsParent(1);
            mapper.update(updateParentCategory);
        }
    }

    //TODO 删除业务规则，当存在子级列别(当前类别isParent为1)时，不允许删除
    //TODO 删除业务规则 当所有子级类别全部被删除时，isParent需要从1更新成0


}
